package demo;

/**
 * @Author liangzai
 * @Description:
 */
public class Training {
    //在排序数组中查找元素的第一个和最后一个位置
    public static int[] searchRange(int[] nums, int target) {
        int[] ret = {-1,-1};
        if(nums==null) {
            return ret;
        }
        int n = nums.length;
        int left = 0;
        int right = n-1;
        while(left<right) {
            int mid = left+(right - left)/2;
            if(nums[mid]<target) {
                left = mid+1;
            }else {
                right = mid;
            }
        }
        if(nums[left]!=target) {
            return ret;
        }else {
            ret[0] = left;
        }
        left = 0;
        right = n-1;
        while(left<right) {
            int mid = left+(right - left+1)/2;
            if(nums[mid]<=target) {
                left = mid;
            }else {
                right = mid-1;
            }
        }
        ret[1] = left;
        return ret;
    }

    //寻找旋转排序数组中的最小值
    public int findMin(int[] nums) {
        int n = nums.length;
        int left = 0;
        int right = n-1;
        while(left<right) {
            int mid = left+(right - left)/2;
            if(nums[mid]<=nums[n-1]) {
                right = mid;
            }else {
                left = mid+1;
            }
        }
        return nums[left];
    }
}
